<template>
  <div class="cate">
    <!-- 数据尽量扁平化处理，所以数据都展开一个个传这样更合理 -->
      <van-list
        v-model="loading"
        :finished="isEnd"
        finished-text="没有更多了"
        @load="getData"
      >
          <van-cell
            v-for="shop in cateList"
            :key="`shop-${shop.id}`"
          >
          <template #title>
            <AddCard
              :id="shop.id"
              :title="shop.title"
              :image="shop.image"
              :saleNum="shop.saleNum"
              :price="shop.price"
              :type="shop.type"
            />
          </template>
        </van-cell>
      <van-cell/>
    </van-list>
  </div>
</template>

<script>
import AddCard from './AddCard'
export default {
  name: 'Category',
  data () {
    return {
      id: '',
      cateList: [],
      // 请求数据其实索引
      start: 0,
      // 是否加载完成
      isEnd: false,
      // 函数节流:如果正在加载不允许发送重复的请求
      loading: false
    }
  },
  components: {
    AddCard
  },
  created () {
    this.id = this.$route.params.id
    // 我们使用的组件vant-list组件会默认发一次请求，这里不用发
    // this.getData()
  },
  beforeRouteUpdate (to, from, next) {
    this.id = to.params.id
    next()
    // 先把start重置，cateList清空
    this.start = 0
    this.cateList = []
    this.getData()
  },
  methods: {
    getData () {
      this.$http.getCategory(this.id, this.start)
        .then(resp => {
          const { list, nextIndex, isEnd } = resp.items
          this.cateList = this.cateList.concat(list)
          this.start = nextIndex
          this.isEnd = isEnd
          this.loading = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.cate {
  .van-list {
    display: flex;
    flex-wrap: wrap;
  }
  .van-cell {
    width: 46%;
    margin: 2%;
    padding: 2%;
    font-size: 12px;
    line-height: 2;
    color:#666;
    border-radius: 5px;
  }
  .van-cell__title {
    width: 100%;
  }
}
</style>
